package com.bolt.report.business.modules.report.service;

import com.bolt.common.lang.Assert;
import com.bolt.convention.exception.ServiceException;
import com.bolt.core.view.components.BindDataModel;
import com.bolt.core.view.components.FormItem;
import com.bolt.core.view.components.ListDataLoad;
import com.bolt.report.business.ReportDBDefManager;
import com.bolt.report.definition.ReportDefinition;
import com.bolt.report.engine.CollectionDataSource;
import com.bolt.report.engine.ReportConstants;
import com.bolt.report.exception.ReportException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.LinkedHashMap;
import java.util.Map;

@Service(ReportConstants.FORM_SELECT_ITEM_BIND_DATA_NAME)
@Slf4j
public class FormSelectItemBindData implements ListDataLoad {

    @Autowired
    private FormItemBindDataService formItemBindDataService;


    @Autowired
    private ReportDBDefManager ReportDBDefManager;

    public FormItem getFormItem(Map params) {
        if (!params.containsKey(ReportConstants.REPORT_ID_PARAM)) {
            throw new ReportException("表报参数未指定");
        }
        if (!params.containsKey(ReportConstants.FORM_SELECT_REF_ID)) {
            throw new ReportException("控制参数未指定");
        }
        String reportId = (String) params.get(ReportConstants.REPORT_ID_PARAM);
        String itemId = (String) params.get(ReportConstants.FORM_SELECT_REF_ID);
        ReportDefinition definition = ReportDBDefManager.loadReportDefinition(reportId);
        FormItem formItem = definition.findFormItem(itemId);
        return formItem;
    }


    @Override
    public Map<String, String> load(FormItem item, Map param) {
        try {
            BindDataModel bindData = item.getBindDataModel();
            Assert.isNull(bindData, "控件数据绑定未配置");
            param.putAll(item.getParameters());
            CollectionDataSource dataSource = (CollectionDataSource) formItemBindDataService.executeDataSet(bindData, param);
            Map<String, String> data = new LinkedHashMap<>();
            while (dataSource.next()) {
                data.put(dataSource.getFieldValue(bindData.getKeyField()), dataSource.getFieldValue(bindData.getLabelField()));
            }
            return data;
        } catch (Exception ex) {
            log.error(ex.getMessage(), ex);
            throw new ServiceException(ex);
        }
    }


}